package com.my.pdfexplorer;

import static com.my.pdfexplorer.ThumbnailActivity.RESULT_PAGE_KEY;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.BitmapFactory;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.CacheDiskUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.reflect.TypeToken;
import com.my.pdfexplorer.adapter.ImageThumbnailRecyclerAdapter;
import com.my.pdfexplorer.adapter.SearchResultRecyclerAdapter;
import com.my.pdfexplorer.databinding.ActivityMainBinding;
import com.my.pdfexplorer.fragments.MainActivity_Fragment_Book_Mark;
import com.my.pdfexplorer.fragments.MainActivity_Fragment_Collection;
import com.my.pdfexplorer.fragments.MainActivity_Fragment_Notes;
import com.my.pdfexplorer.models.CollectionItem;
import com.my.pdfexplorer.models.NotesItem;
import com.my.pdfexplorer.models.PopupWindowPdfPositionStatus;
import com.my.pdfexplorer.models.ReadModeItem;
import com.my.pdfexplorer.models.ReserveAnnotation;
import com.my.pdfexplorer.models.ReserveAnnotationType;
import com.my.pdfexplorer.models.SearchResultItem;
import com.my.pdfexplorer.utils.BitmapMemoryCacheHelper;
import com.my.pdfexplorer.utils.ColorUtil;
import com.my.pdfexplorer.utils.PopupWindowUtil;
import com.my.pdfexplorer.utils.TimeUtil;
import com.my.pdfexplorer.utils.ToastUtil;
import com.my.pdfexplorer.views.CircleView;
import com.my.pdfexplorer.views.StatusView;
import com.my.pdfexplorer.views.bubble_seekbar.BubbleSeekBar;
import com.my.pdfexplorer.views.third_switch_seekbar.ThirdSwitchSeekBar;
import com.snakeway.pdfviewer.PDFView;
import com.snakeway.pdfviewer.RenderingCustomHandler;
import com.snakeway.pdfviewer.annotation.AnnotationBean;
import com.snakeway.pdfviewer.annotation.AnnotationListener;
import com.snakeway.pdfviewer.annotation.NotesAnnotation;
import com.snakeway.pdfviewer.annotation.PenAnnotation;
import com.snakeway.pdfviewer.annotation.base.BaseAnnotation;
import com.snakeway.pdfviewer.annotation.base.MarkAreaType;
import com.snakeway.pdfviewer.annotation.eraser.PenRectEraser;
import com.snakeway.pdfviewer.annotation.pen.AreaPen;
import com.snakeway.pdfviewer.annotation.pen.DeleteLinePen;
import com.snakeway.pdfviewer.annotation.pen.HighLightPen;
import com.snakeway.pdfviewer.annotation.pen.Pen;
import com.snakeway.pdfviewer.annotation.pen.PenBuilder;
import com.snakeway.pdfviewer.annotation.pen.TextPen;
import com.snakeway.pdfviewer.annotation.pen.UnderLinePen;
import com.snakeway.pdfviewer.annotation.pen.UnderWaveLinePen;
import com.snakeway.pdfviewer.listener.OnAreaTouchListener;
import com.snakeway.pdfviewer.listener.OnErrorListener;
import com.snakeway.pdfviewer.listener.OnLoadCompleteListener;
import com.snakeway.pdfviewer.listener.OnPageChangeListener;
import com.snakeway.pdfviewer.listener.OnPageErrorListener;
import com.snakeway.pdfviewer.listener.OnSearchTagSectionsListener;
import com.snakeway.pdfviewer.listener.OnSearchTextListener;
import com.snakeway.pdfviewer.model.ClickInfo;
import com.snakeway.pdfviewer.model.MarkAreaInfo;
import com.snakeway.pdfviewer.model.NotesRemarkInfo;
import com.snakeway.pdfviewer.model.SearchTextInfo;
import com.snakeway.pdfviewer.model.TagSectionInfo;
import com.snakeway.pdfviewer.util.FitPolicy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends BaseActivity<ActivityMainBinding> implements OnPageChangeListener, OnLoadCompleteListener,
        OnPageErrorListener {
    public static final int THUMBNAIL_CHOOSE_REQUEST = 2222;

    public static final String CACHE_COLLECTION_TAG = "collection:";
    public static final String NOTES_TAG = "notes:";

    public static final String FILE_PATH_KEY = "file_path_key";
    public static final String FILE_PASSWORD_KEY = "file_password_key";
    public static final String SELECT_PAGE_KEY = "select_page_key";

    public static final String READ_MODE_ITEMS_KEY = "read_mode_items_key";

    public static final float PEN_SCALE_DEFAULT = 0.4f;
    public static final String COLLECTION_ITEMS_KEY = "collection_items_key";
    public static final String NOTES_ITEMS_KEY = "notes_items_key";

    public final String PDF_NAME = "test.pdf";
    public final String PDF_PASSWORD = "123456";

    //只允许单个选定标记区域
    public static final boolean SELECT_AREA_MARK_SINGLE = false;


    public static final boolean OPEN_OPTIMIZATION_ANNOTATION = true;

    private View.OnClickListener onClickListener;
    private PDFView.Configurator configurator;
    private Integer pageNumber = 0;

    private String popupWindowSelectMarkKey;
    private List<String> annotations = new ArrayList<>();

    private String popupWindow;

    final List<CircleView> circleViews = new ArrayList<>();
    final List<CircleView> textCircleViews = new ArrayList<>();

    private int selectPenColorIndex;
    private int selectTextColorIndex;
    private Pen.WritePen pen;
    private TextPen textPen;

    private int selectMenu;

    private int penSize = 2;
    private int textSize = 10;
    private int penColor;
    private int textColor;

    private String searchContent;

    private int selectMarkPenModeIndex = 0;

    final List<ReadModeItem> readModeItems = new ArrayList<>();

    final List<ReserveAnnotation> reserveAnnotations = new ArrayList<>();
    final List<String> titles = new ArrayList<>();
    final List<Integer> tabIcons = new ArrayList<>();
    final List<Fragment> fragments = new ArrayList<>();

    final HashMap<String, List<CollectionItem>> hashMapCollectionItems = new HashMap<String, List<CollectionItem>>();
    final HashMap<String, List<NotesItem>> hashMapNotesItems = new HashMap<String, List<NotesItem>>();

    private SearchResultRecyclerAdapter searchResultRecyclerAdapter;

    private boolean eraserSuccess = false;//如果是橡皮擦模式当取消橡皮擦后再保存批注以免卡顿

    private BitmapMemoryCacheHelper bitmapMemoryCacheHelper = new BitmapMemoryCacheHelper();

    private ImageThumbnailRecyclerAdapter imageThumbnailRecyclerAdapter;

    //需要使用引用以保持click事件获取的是最新的
    private final PopupWindowPdfPositionStatus popupWindowPdfPositionStatus = new PopupWindowPdfPositionStatus();

    //需要使用引用以保持颜色选择click事件获取的是最新的
    private final List<MarkAreaType> selectMarkAreaTypes = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initAll();
    }

    @Override
    protected ActivityMainBinding getViewBinder() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    public void initHandler() {
        handler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void initUi() {
        onClickListener();
        onSearchListener();
    }

    @Override
    public void initConfigUi() {
        initReadModeItems();
        restoreHashMapCollectionItemsData();
        restoreHashMapNotesItemsData();
        openPdf(PDF_NAME, PDF_PASSWORD);

        viewBinding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);

        viewBinding.pdfView.setMinZoom(1F);
        viewBinding.pdfView.setMidZoom(2F);
        viewBinding.pdfView.setMaxZoom(3F);

        AreaPen areaPen = PenBuilder.areaPenBuilder().setColor(getResources().getColor(R.color.areaPen_default)).build();
        areaPen.setCursorColor(getResources().getColor(R.color.areaPen_cursor_default));

        DeleteLinePen deleteLinePen = PenBuilder.deleteLinePenBuilder().setColor(getResources().getColor(R.color.deleteLinePen_default)).build();
        UnderLinePen underLinePen = PenBuilder.underLinePenBuilder().setColor(getResources().getColor(R.color.underLinePen_default)).build();
        UnderWaveLinePen underWaveLinePen = PenBuilder.underWaveLinePenBuilder().setColor(getResources().getColor(R.color.wavesLinePen_default)).build();
        HighLightPen highLightPen = PenBuilder.selectedPenBuilder().setColor(ColorUtil.getColorWithAlpha(0.5F, getResources().getColor(R.color.highLightPen_default))).build();

        viewBinding.pdfView.setAreaPen(areaPen);
        viewBinding.pdfView.setDrawAreaPen(MarkAreaType.DELETELINE, deleteLinePen);
        viewBinding.pdfView.setDrawAreaPen(MarkAreaType.UNDERLINE, underLinePen);
        viewBinding.pdfView.setDrawAreaPen(MarkAreaType.UNDERWAVELINE, underWaveLinePen);
        viewBinding.pdfView.setDrawAreaPen(MarkAreaType.HIGHLIGHT, highLightPen);
        viewBinding.pdfView.setNotesBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.notes));
        viewBinding.pdfView.setSearchAreaPen(PenBuilder.searchAreaPenBuilder().setColor(getResources().getColor(R.color.searchAreaPen_default)).build());
        viewBinding.pdfView.addAnnotations(getAnnotationData(), false);
        viewBinding.pdfView.setProgressViewBackground(getResources().getColor(R.color.pdf_view_background));
        viewBinding.pdfView.setEnablePenAnnotationClickCheckOnViewMode(false);
        viewBinding.pdfView.setAnnotationListener(new AnnotationListener() {
            @Override
            public void onAnnotationAdd(BaseAnnotation baseAnnotation) {
                String result = GsonUtils.toJson(viewBinding.pdfView.getOptimizationAnnotation(baseAnnotation));
                annotations.add(result);
                saveAnnotationData();
            }

            @Override
            public void onAnnotationRemove(BaseAnnotation baseAnnotation) {
                if (isEraserMode()) {
                    eraserSuccess = true;
                } else {
                    saveAnnotationData();
                }
            }

            @Override
            public void onAnnotationPageRemove(int page) {
                saveAnnotationData();
            }

            @Override
            public void onAnnotationAllRemove() {
                saveAnnotationData();
            }

            @Override
            public void onAnnotationAddDrawing(BaseAnnotation baseAnnotation) {
                // viewBinding.pdfView.savePenDrawing();
            }
        });
        viewBinding.pdfView.setOnAreaTouchListener(new OnAreaTouchListener() {
            @Override
            public void onActiveArea() {
                doVibrate();
            }

            @Override
            public void onAreaSelect(@NonNull RectF startRect, @NonNull RectF endRect, float translateX, float translateY, float targetViewSize, List<MarkAreaType> selectMarkAreaTypes, MarkAreaInfo markAreaInfo) {
                MainActivity.this.selectMarkAreaTypes.clear();
                MainActivity.this.selectMarkAreaTypes.addAll(selectMarkAreaTypes);
                int[] position = getPopupWindowShowPosition(startRect, endRect, translateX, translateY, targetViewSize);
                showPopupWindowSelectMark(viewBinding.rootView, position[0], position[1], position[2] == 1, MainActivity.this.selectMarkAreaTypes, selectMarkPenModeIndex, markAreaInfo);
            }

            @Override
            public void onReTouchStart() {
                visiblePopupWindowSelectMark(false);
            }

            @Override
            public void onReTouchAreaSelectUpdate(@NonNull RectF startRect, @NonNull RectF endRect, float translateX, float translateY, float targetViewSize, @NonNull List<MarkAreaType> selectMarkAreaTypes, MarkAreaInfo markAreaInfo) {
                MainActivity.this.selectMarkAreaTypes.clear();
                MainActivity.this.selectMarkAreaTypes.addAll(selectMarkAreaTypes);
                updateSelectMarkPopupWindowPosition(startRect, endRect, translateX, translateY, targetViewSize, MainActivity.this.selectMarkAreaTypes, markAreaInfo);
            }

            @Override
            public void reSelectMarkArea(@NonNull RectF startRect, @NonNull RectF endRect, float translateX, float translateY, float targetViewSize, List<MarkAreaType> selectMarkAreaTypes, MarkAreaInfo markAreaInfo) {
                MainActivity.this.selectMarkAreaTypes.clear();
                MainActivity.this.selectMarkAreaTypes.addAll(selectMarkAreaTypes);
                int[] position = getPopupWindowShowPosition(startRect, endRect, translateX, translateY, targetViewSize);
                showPopupWindowSelectMark(viewBinding.rootView, position[0], position[1], position[2] == 1, MainActivity.this.selectMarkAreaTypes, selectMarkPenModeIndex, markAreaInfo);
            }

            @Override
            public void onReTouchComplete() {
                visiblePopupWindowSelectMark(true);
            }

            @Override
            public void onDismiss() {
                dismissPopupWindowSelectMark();
            }
        });
        viewBinding.pdfView.setOnPdfViewClickListener(new PDFView.OnPdfViewClickListener() {
            @Override
            public void onClick(View v, ClickInfo clickInfo) {
            }
        });
        viewBinding.pdfView.setOnNotesClickListener(new PDFView.OnNotesClickListener() {
            @Override
            public void onClick(View v, NotesRemarkInfo notesRemarkInfo, boolean isSelect) {
                showPopupWindowInputNotes(viewBinding.layoutTopAppbar.linearLayoutCollection, isSelect, notesRemarkInfo.getData(), notesRemarkInfo.getKey(), notesRemarkInfo);
            }
        });

        viewBinding.pdfView.setOnLoadCompletedListener(new PDFView.OnLoadCompletedListener() {

            @Override
            public void onLoad() {
                viewBinding.loadProgressBar.setVisibility(View.VISIBLE);
//                viewBinding.pdfBottomPageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onCompleted() {
                viewBinding.loadProgressBar.setVisibility(View.INVISIBLE);
                viewBinding.pdfBottomPageView.setVisibility(View.VISIBLE);
            }
        });
        viewBinding.pdfView.setOnPdfPageScrollListener(new PDFView.OnPdfPageScrollListener() {
            @Override
            public void onPageScrolled(int page, float positionOffset) {
                viewBinding.pdfBottomPageView.setText((page + 1) + "/" + viewBinding.pdfView.getPageCount());
            }
        });
        viewBinding.layoutPenOperating.layoutThirdSwitch.thirdSwitchSeekBar.setSeekTouchListen(new ThirdSwitchSeekBar.SeekTouchListener() {
            @Override
            public void touchTop(SeekBar seekBar) {
                penSize = 2;
                pen = PenBuilder.brushPenBuilder().setColor(penColor).setPenWidthScale(PEN_SCALE_DEFAULT * penSize).build();
                viewBinding.pdfView.setPen(pen);
            }

            @Override
            public void touchMiddle(SeekBar seekBar) {
                penSize = 5;
                pen = PenBuilder.brushPenBuilder().setColor(penColor).setPenWidthScale(PEN_SCALE_DEFAULT * penSize).build();
                viewBinding.pdfView.setPen(pen);
            }

            @Override
            public void touchEnd(SeekBar seekBar) {
                penSize = 7;
                pen = PenBuilder.brushPenBuilder().setColor(penColor).setPenWidthScale(PEN_SCALE_DEFAULT * penSize).build();
                viewBinding.pdfView.setPen(pen);
            }

//            @Override
//            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
//
//            }
        });

//        viewBinding.layoutPenOperating.mySeekBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
//            @Override
//            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
//                viewBinding.layoutPenOperating.textViewTextSize.setText(progress + "px");
//                penSize = progress;
//                pen = PenBuilder.brushPenBuilder().setColor(penColor).setPenWidthScale(PEN_SCALE_DEFAULT * penSize).build();
//                viewBinding.pdfView.setPen(pen);
//            }
//
//            @Override
//            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
//
//            }
//
//            @Override
//            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
//
//            }
//        });

        viewBinding.layoutTextOperating.mySeekBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                viewBinding.layoutTextOperating.textViewTextSize.setText(progress + "px");
                textSize = progress;
                textPen = PenBuilder.textPenBuilder().setColor(textColor).setFontSize(textSize).build();
                viewBinding.pdfView.setTextPen(textPen);
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {

            }
            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
            }
        });
        initPenColorViews();
        initTextColorViews();
        initTabView();
    }

    void initTabView() {
        viewBinding.layoutTopAppbar.textViewToolbarTitle.setText(PDF_NAME);
        viewBinding.pdfBottomPageView.setText("1/" + viewBinding.pdfView.getPageCount());

        titles.clear();
        tabIcons.clear();
        fragments.clear();

        titles.add(getString(R.string.main_activity_fragment_title_collection));
        titles.add(getString(R.string.main_activity_fragment_title_catalog));
        titles.add(getString(R.string.main_activity_fragment_title_note));

        tabIcons.add(R.mipmap.drawer_view_tab_collection);
        tabIcons.add(R.mipmap.drawer_view_tab_book_mark);
        tabIcons.add(R.mipmap.drawer_view_tab_notes);

        fragments.add(new MainActivity_Fragment_Collection());
        fragments.add(new MainActivity_Fragment_Book_Mark());
        fragments.add(new MainActivity_Fragment_Notes());

        for (int i = 0; i < titles.size(); i++) {
            viewBinding.layoutDrawerView.tabLayout.addTab(viewBinding.layoutDrawerView.tabLayout.newTab());
        }
        viewBinding.layoutDrawerView.viewPager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragments.get(position);
            }

            @Override
            public int getItemCount() {
                return titles.size();
            }
        });
        viewBinding.layoutDrawerView.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
            }
        });
        TabLayoutMediator mediator = new TabLayoutMediator(viewBinding.layoutDrawerView.tabLayout, viewBinding.layoutDrawerView.viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                TabLayout.Tab theTab = tab.setCustomView(R.layout.layout_drawer_view_tab_item);
                ImageView imageView = theTab.getCustomView().findViewById(R.id.imageView);
                TextView textView = theTab.getCustomView().findViewById(R.id.textView);
                imageView.setImageResource(tabIcons.get(position));
                textView.setText(titles.get(position));
            }
        });
        mediator.attach();
    }

    void setNightMode(boolean isNight) {
//        int color = isNight ? getResources().getColor(R.color.night_background) : getResources().getColor(R.color.mainColorHelp_default);
//        int pdfBackgroundColor = isNight ? getResources().getColor(R.color.night_deep_background) : getResources().getColor(R.color.pdf_view_background);
//
//        viewBinding.layoutTopAppbar.appBarLayout.setBackgroundColor(color);
//        viewBinding.pdfView.setBackgroundColor(pdfBackgroundColor);
//        viewBinding.layoutDrawerView.relativeLayoutDrawer.setBackgroundColor(color);
//        viewBinding.layoutDrawerView.tabLayout.setBackgroundColor(color);
//        viewBinding.layoutBottomMenu.appBarLayout.setBackgroundColor(color);
    }

    void showPopupWindowSelectMark(View view, int x, int y, boolean isUp, List<MarkAreaType> selectMarkAreaTypes, int selectMarkPenModeIndex, MarkAreaInfo markAreaInfo) {
        popupWindowSelectMarkKey = PopupWindowUtil.POPUPWINDOWKEY + TimeUtil.getOnlyTimeWithoutSleep();
        PopupWindowUtil.showPopupWindowSelectMark(MainActivity.this, view.getRootView(), view, popupWindowSelectMarkKey, popupWindowPdfPositionStatus, selectMarkAreaTypes, selectMarkPenModeIndex, markAreaInfo,
                new PopupWindowUtil.OnShowPopupWindowSelectMarkListener() {
                    @Override
                    public boolean onSelect(PopupWindow popupWindow, View view, MarkAreaType markAreaType) {
                        if (!MainActivity.this.selectMarkAreaTypes.contains(markAreaType)) {
                            MainActivity.this.selectMarkAreaTypes.add(markAreaType);
                        }
                        return viewBinding.pdfView.drawSelectAreaWithMarkAreaType(markAreaType);
                    }

                    @Override
                    public boolean onCancelSelect(PopupWindow popupWindow, View view, MarkAreaType markAreaType) {
                        MainActivity.this.selectMarkAreaTypes.remove(markAreaType);
                        return viewBinding.pdfView.cancelSelectAreaAnnotation(markAreaType);
                    }

                    @Override
                    public void clearPage(PopupWindow popupWindow, View view) {
                        viewBinding.pdfView.clearPage();
                        popupWindow.dismiss();
                    }

                    @Override
                    public void onDismiss(PopupWindow popupWindow, View view) {
                        viewBinding.pdfView.dismissAreaSelect();
                    }
                }, new PopupWindowUtil.OnSelectMarkPenModeListener() {
                    @Override
                    public void onClick(View view, List<MarkAreaType> selectMarkAreaTypes, int index) {
                        updateRemarkPenMode(selectMarkAreaTypes, index);
                    }
                });
    }

    void initReadModeItems() {
        restoreReadModeItemData();
        if (readModeItems.size() == 0) {
            readModeItems.add(new ReadModeItem(ReadModeItem.ReadModeType.SINGLE, R.mipmap.mode_single_page, getResources().getString(R.string.layout_read_mode_item_single), true));
            readModeItems.add(new ReadModeItem(ReadModeItem.ReadModeType.MULTI, R.mipmap.mode_multi_page, getResources().getString(R.string.layout_read_mode_item_multi), false));
            readModeItems.add(new ReadModeItem(ReadModeItem.ReadModeType.THUMBNAIL, R.mipmap.mode_thumbnail, getResources().getString(R.string.layout_read_mode_item_thumbnail), false));
            readModeItems.add(new ReadModeItem(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE, R.mipmap.mode_night, getResources().getString(R.string.layout_read_mode_item_auto_fill_white_space), false));
            readModeItems.add(new ReadModeItem(ReadModeItem.ReadModeType.NIGHT, R.mipmap.mode_night, getResources().getString(R.string.layout_read_mode_item_night), false));
            saveReadModeItemData();
        }
        viewBinding.layoutReadMode.imageViewSingleCheck.setImageResource(isReadModeChecked(ReadModeItem.ReadModeType.SINGLE) ? R.mipmap.mode_select : R.mipmap.mode_un_select);
        viewBinding.layoutReadMode.imageViewMultiCheck.setImageResource(isReadModeChecked(ReadModeItem.ReadModeType.MULTI) ? R.mipmap.mode_select : R.mipmap.mode_un_select);
        viewBinding.layoutReadMode.imageViewAutoFillCheck.setImageResource(isReadModeChecked(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE) ? R.mipmap.mode_select : R.mipmap.mode_un_select);
        viewBinding.layoutReadMode.imageViewNightCheck.setImageResource(isReadModeChecked(ReadModeItem.ReadModeType.NIGHT) ? R.mipmap.mode_select : R.mipmap.mode_un_select);
    }

    void updateReadModeStatus(ReadModeItem.ReadModeType readModeType) {
        switch (readModeType) {
            case SINGLE:
                setReadModeChecked(ReadModeItem.ReadModeType.MULTI, false);
                setReadModeChecked(ReadModeItem.ReadModeType.SINGLE, true);
                break;
            case MULTI:
                setReadModeChecked(ReadModeItem.ReadModeType.SINGLE, false);
                setReadModeChecked(ReadModeItem.ReadModeType.MULTI, true);
                break;
            case AUTO_FILL_WHITE_SPACE:
                setReadModeChecked(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE, !isReadModeChecked(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE));
                break;
            case NIGHT:
                setReadModeChecked(ReadModeItem.ReadModeType.NIGHT, !isReadModeChecked(ReadModeItem.ReadModeType.NIGHT));
                break;
            default:
                break;
        }
        saveReadModeItemData();
        viewBinding.layoutReadMode.imageViewSingleCheck.setImageResource(isReadModeChecked(ReadModeItem.ReadModeType.SINGLE) ? R.mipmap.mode_select : R.mipmap.mode_un_select);
        viewBinding.layoutReadMode.imageViewMultiCheck.setImageResource(isReadModeChecked(ReadModeItem.ReadModeType.MULTI) ? R.mipmap.mode_select : R.mipmap.mode_un_select);
        viewBinding.layoutReadMode.imageViewAutoFillCheck.setImageResource(isReadModeChecked(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE) ? R.mipmap.mode_select : R.mipmap.mode_un_select);
        viewBinding.layoutReadMode.imageViewNightCheck.setImageResource(isReadModeChecked(ReadModeItem.ReadModeType.NIGHT) ? R.mipmap.mode_select : R.mipmap.mode_un_select);
    }

    private void onSearchListener() {
        viewBinding.layoutSearchAppbar.editTextSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                searchContent = viewBinding.layoutSearchAppbar.editTextSearch.getText().toString();
            }
        });
        viewBinding.layoutSearchAppbar.editTextSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    searchTagSectionInfos(searchContent);
                    return true;
                }
                return false;
            }
        });
    }

    public void addNotesItem(String filePath, String value, NotesRemarkInfo notesRemarkInfo) {
        if (notesRemarkInfo == null) {
            return;
        }
        List<NotesItem> notesItems = hashMapNotesItems.get(NOTES_TAG + filePath);
        if (notesItems == null) {
            notesItems = new ArrayList<>();
        }

        NotesAnnotation notesAnnotation = viewBinding.pdfView.getNotesAnnotation(notesRemarkInfo);
//        notesRemarkInfo.setKey(notesAnnotation.id);
        notesRemarkInfo.setData(value);
        viewBinding.pdfView.addLastAnnotation(notesAnnotation, true);

        NotesItem notesItem = new NotesItem(notesAnnotation.id, filePath, value, notesRemarkInfo.getPage(), notesRemarkInfo.getPdfPositionX(), notesRemarkInfo.getPdfPositionY(), notesRemarkInfo.getPdfWidth(), notesRemarkInfo.getPdfHeight());
        notesItems.add(notesItem);
        hashMapNotesItems.put(NOTES_TAG + filePath, notesItems);
        saveHashMapNotesItemsData();
    }

    public void editNotesItem(String filePath, String id, String value) {
        List<NotesItem> notesItems = hashMapNotesItems.get(NOTES_TAG + filePath);
        if (notesItems == null) {
            notesItems = new ArrayList<>();
        }
        for (int i = 0; i < notesItems.size(); i++) {
            if (notesItems.get(i).getId() != null && notesItems.get(i).getId().equals(id)) {
                notesItems.get(i).setValue(value);
                break;
            }
        }
        BaseAnnotation baseAnnotation = viewBinding.pdfView.getAnnotationById(id);
        if (baseAnnotation != null && baseAnnotation instanceof NotesAnnotation) {
            ((NotesAnnotation) baseAnnotation).data.setData(value);
            saveAnnotationData();
        }
        saveHashMapNotesItemsData();
    }

    public void removeNotesItem(String filePath, String id) {
        List<NotesItem> notesItems = hashMapNotesItems.get(NOTES_TAG + filePath);
        if (notesItems == null) {
            notesItems = new ArrayList<>();
        }
        int removeIndex = -1;
        for (int i = 0; i < notesItems.size(); i++) {
            if (notesItems.get(i).getId() != null && notesItems.get(i).getId().equals(id)) {
                removeIndex = i;
                break;
            }
        }
        if (removeIndex != -1) {
            viewBinding.pdfView.removeAnnotationById(notesItems.get(removeIndex).getId(), true);
            notesItems.remove(removeIndex);
        }
        saveHashMapNotesItemsData();
    }

    public void editCollectionItem(String filePath, String name, CollectionItem collectionItem) {
        if (collectionItem == null) {
            return;
        }
        collectionItem.setName(name);
        saveHashMapCollectionItemsData();
        updateCollection();
    }

    public void addCollectionItem(String filePath, String name, int page) {
        List<CollectionItem> collectionItems = hashMapCollectionItems.get(CACHE_COLLECTION_TAG + filePath);
        if (collectionItems == null) {
            collectionItems = new ArrayList<>();
        }
        int updateIndex = -1;

        for (int i = 0; i < collectionItems.size(); i++) {
            if (collectionItems.get(i).getPage() == page) {
                updateIndex = i;
                break;
            }
        }
        if (updateIndex == -1) {
            collectionItems.add(new CollectionItem(filePath, name, page));
        } else {
            collectionItems.get(updateIndex).setName(name);
        }
        hashMapCollectionItems.put(CACHE_COLLECTION_TAG + filePath, collectionItems);
        saveHashMapCollectionItemsData();
        updateCollection();
    }

    public void removeCollectionItem(String filePath, int page) {
        List<CollectionItem> collectionItems = hashMapCollectionItems.get(CACHE_COLLECTION_TAG + filePath);
        if (collectionItems == null) {
            collectionItems = new ArrayList<>();
        }
        int removeIndex = -1;
        for (int i = 0; i < collectionItems.size(); i++) {
            if (collectionItems.get(i).getPage() == page) {
                removeIndex = i;
                break;
            }
        }
        if (removeIndex != -1) {
            collectionItems.remove(removeIndex);
        }
        saveHashMapCollectionItemsData();
        updateCollection();
    }

    public List<NotesItem> getCurrentNotesItems(String filePath) {
        List<NotesItem> notesItems = hashMapNotesItems.get(NOTES_TAG + filePath);
        if (notesItems == null) {
            notesItems = new ArrayList<>();
        }

        for (int i = 0; i < notesItems.size() - 1; i++) {
            for (int j = 1; j < notesItems.size() - i; j++) {
                int a = notesItems.get(j - 1).getPage();
                int b = notesItems.get(j).getPage();
                if (a > b) {
                    NotesItem temp = notesItems.get(j - 1);
                    notesItems.set((j - 1), notesItems.get(j));
                    notesItems.set(j, temp);
                }
            }
        }
        return notesItems;
    }

    public List<CollectionItem> getCurrentCollectionItems(String filePath) {
        List<CollectionItem> collectionItems = hashMapCollectionItems.get(CACHE_COLLECTION_TAG + filePath);
        if (collectionItems == null) {
            collectionItems = new ArrayList<>();
        }

        for (int i = 0; i < collectionItems.size() - 1; i++) {
            for (int j = 1; j < collectionItems.size() - i; j++) {
                int a = collectionItems.get(j - 1).getPage();
                int b = collectionItems.get(j).getPage();
                if (a > b) {
                    CollectionItem temp = collectionItems.get(j - 1);
                    collectionItems.set((j - 1), collectionItems.get(j));
                    collectionItems.set(j, temp);
                }
            }
        }
        return collectionItems;
    }

    private boolean isCollection(String filePath, int page) {
        List<CollectionItem> collectionItems = hashMapCollectionItems.get(CACHE_COLLECTION_TAG + filePath);
        if (collectionItems == null) {
            collectionItems = new ArrayList<>();
        }
        for (int i = 0; i < collectionItems.size(); i++) {
            if (collectionItems.get(i).getPage() == page) {
                return true;
            }
        }
        return false;
    }

    private void saveHashMapNotesItemsData() {
        String result = GsonUtils.toJson(hashMapNotesItems);
        CacheDiskUtils.getInstance().put(NOTES_ITEMS_KEY, result);
        if (fragments.size() > 2 && fragments.get(2) instanceof MainActivity_Fragment_Notes) {
            ((MainActivity_Fragment_Notes) fragments.get(2)).resetAdapter();
        }
    }

    private void restoreHashMapNotesItemsData() {
        String text = CacheDiskUtils.getInstance().getString(NOTES_ITEMS_KEY, null);
        try {
            if (ObjectUtils.isNotEmpty(text)) {
                HashMap<String, List<NotesItem>> data = GsonUtils.fromJson(text, new TypeToken<HashMap<String, List<NotesItem>>>() {
                }.getType());
                hashMapNotesItems.clear();
                hashMapNotesItems.putAll(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveHashMapCollectionItemsData() {
        String result = GsonUtils.toJson(hashMapCollectionItems);
        CacheDiskUtils.getInstance().put(COLLECTION_ITEMS_KEY, result);
        if (fragments.size() > 0 && fragments.get(0) instanceof MainActivity_Fragment_Collection) {
            ((MainActivity_Fragment_Collection) fragments.get(0)).resetAdapter();
        }
    }

    private void restoreHashMapCollectionItemsData() {
        String text = CacheDiskUtils.getInstance().getString(COLLECTION_ITEMS_KEY, null);
        try {
            if (ObjectUtils.isNotEmpty(text)) {
                HashMap<String, List<CollectionItem>> data = GsonUtils.fromJson(text, new TypeToken<HashMap<String, List<CollectionItem>>>() {
                }.getType());
                hashMapCollectionItems.clear();
                hashMapCollectionItems.putAll(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveReadModeItemData() {
        String result = GsonUtils.toJson(readModeItems);
        CacheDiskUtils.getInstance().put(READ_MODE_ITEMS_KEY, result);
    }

    private void restoreReadModeItemData() {
        String text = CacheDiskUtils.getInstance().getString(READ_MODE_ITEMS_KEY, null);
        try {
            if (ObjectUtils.isNotEmpty(text)) {
                List<ReadModeItem> theReadModeItems = GsonUtils.fromJson(text, new TypeToken<List<ReadModeItem>>() {
                }.getType());
                readModeItems.clear();
                readModeItems.addAll(theReadModeItems);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    boolean isReadModeChecked(ReadModeItem.ReadModeType readModeType) {
        for (ReadModeItem readModeItem : readModeItems) {
            if (readModeItem.getType() == readModeType) {
                return readModeItem.isCheck();
            }
        }
        return false;
    }

    void setReadModeChecked(ReadModeItem.ReadModeType readModeType, boolean check) {
        for (ReadModeItem readModeItem : readModeItems) {
            if (readModeItem.getType() == readModeType) {
                readModeItem.setCheck(check);
                break;
            }
        }
    }

    void dismissPopupWindowSelectMark() {
        if (popupWindowSelectMarkKey == null) {
            return;
        }
        PopupWindow popupWindow = getPopupWindow(popupWindowSelectMarkKey);
        popupWindowSelectMarkKey = null;
        if (popupWindow == null) {
            return;
        }
        popupWindow.dismiss();
    }

    void updateRemarkPenMode(List<MarkAreaType> selectMarkAreaTypes, int selectMarkPenModeIndex) {
        if (selectMarkPenModeIndex < 0) {
            selectMarkPenModeIndex = 0;
        }
        int color;
        switch (selectMarkPenModeIndex) {
            case 1:
                color = getResources().getColor(R.color.circle_color_mode_2);
                break;
            case 2:
                color = getResources().getColor(R.color.circle_color_mode_3);
                break;
            case 3:
                color = getResources().getColor(R.color.circle_color_mode_4);
                break;
            case 4:
                color = getResources().getColor(R.color.circle_color_mode_5);
                break;
            default:
                color = getResources().getColor(R.color.circle_color_mode_1);
                break;
        }
        DeleteLinePen deleteLinePen = PenBuilder.deleteLinePenBuilder().setColor(color).build();
        UnderLinePen underLinePen = PenBuilder.underLinePenBuilder().setColor(color).build();
        UnderWaveLinePen underWaveLinePen = PenBuilder.underWaveLinePenBuilder().setColor(color).build();
        HighLightPen highLightPen = PenBuilder.selectedPenBuilder().setColor(ColorUtil.getColorWithAlpha(0.5F, color)).build();

        viewBinding.pdfView.setDrawAreaPen(MarkAreaType.DELETELINE, deleteLinePen);
        viewBinding.pdfView.setDrawAreaPen(MarkAreaType.UNDERLINE, underLinePen);
        viewBinding.pdfView.setDrawAreaPen(MarkAreaType.UNDERWAVELINE, underWaveLinePen);
        viewBinding.pdfView.setDrawAreaPen(MarkAreaType.HIGHLIGHT, highLightPen);
        this.selectMarkPenModeIndex = selectMarkPenModeIndex;
        for (int i = 0; i < selectMarkAreaTypes.size(); i++) {
            MarkAreaType selectMarkAreaType = selectMarkAreaTypes.get(i);
            viewBinding.pdfView.cancelSelectAreaAnnotation(selectMarkAreaType);
            viewBinding.pdfView.drawSelectAreaWithMarkAreaType(selectMarkAreaType);
        }
    }

    void updateSelectMarkPopupWindowPosition(@NonNull RectF startRect, @NonNull RectF endRect, float translateX, float translateY, float targetViewSize, List<MarkAreaType> selectMarkAreaTypes, MarkAreaInfo markAreaInfo) {
        if (popupWindowSelectMarkKey == null) {
            return;
        }
        PopupWindow popupWindow = getPopupWindow(popupWindowSelectMarkKey);
        if (popupWindow == null) {
            return;
        }
        View contentView = popupWindow.getContentView();

        final LinearLayout linearLayoutMarkMode = (LinearLayout) contentView.findViewById(R.id.linearLayoutMarkMode);
        final StatusView statusViewMarkMode = (StatusView) contentView.findViewById(R.id.statusViewMarkMode);
        final StatusView statusViewHighLight = (StatusView) contentView.findViewById(R.id.statusViewHighLight);
        final StatusView statusViewWaveLine = (StatusView) contentView.findViewById(R.id.statusViewWaveLine);
        final StatusView statusViewUnderLine = (StatusView) contentView.findViewById(R.id.statusViewUnderLine);
        final StatusView statusViewCopy = (StatusView) contentView.findViewById(R.id.statusViewCopy);

        statusViewHighLight.setChecked(false);
        statusViewWaveLine.setChecked(false);
        statusViewUnderLine.setChecked(false);
        boolean isSelect = false;
        statusViewCopy.setTag(markAreaInfo);

        if (selectMarkAreaTypes != null) {
            for (MarkAreaType markAreaType : selectMarkAreaTypes) {
                if (markAreaType == MarkAreaType.HIGHLIGHT || markAreaType == MarkAreaType.UNDERWAVELINE || markAreaType == MarkAreaType.UNDERLINE || markAreaType == MarkAreaType.DELETELINE) {
                    isSelect = true;
                }
                switch (markAreaType) {
                    case HIGHLIGHT:
                        statusViewHighLight.setChecked(true);
                        break;
                    case UNDERWAVELINE:
                        statusViewWaveLine.setChecked(true);
                        break;
                    case UNDERLINE:
                        statusViewUnderLine.setChecked(true);
                        break;
                    default:
                        break;
                }
            }
        }
        if (isSelect) {
            linearLayoutMarkMode.setVisibility(View.VISIBLE);
            statusViewMarkMode.setCheckImage(R.mipmap.select_mark_line_select);
            statusViewMarkMode.setUnCheckImage(R.mipmap.select_mark_line_select);
            statusViewMarkMode.getText().setText(getString(R.string.popupwindow_select_mark_delete_draw_line));
            linearLayoutMarkMode.setTag(true);
        } else {
            linearLayoutMarkMode.setVisibility(View.GONE);
            statusViewMarkMode.setCheckImage(R.mipmap.select_mark_under_line_old);
            statusViewMarkMode.setUnCheckImage(R.mipmap.select_mark_under_line_old);
            statusViewMarkMode.getText().setText(getString(R.string.popupwindow_select_mark_draw_line));
            linearLayoutMarkMode.setTag(false);
        }

        PopupWindowUtil.setMarkPenModeOnClickListener(contentView, selectMarkPenModeIndex, new PopupWindowUtil.OnSelectMarkPenModeListener() {
            @Override
            public void onClick(View view, List<MarkAreaType> selectMarkAreaTypes, int index) {
                updateRemarkPenMode(selectMarkAreaTypes, index);
            }
        }, selectMarkAreaTypes);

        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);//要放在linearLayoutMarkMode.setVisibility(View.GONE);之后才能计算准确
        contentView.measure(spec, spec);
        int measuredWidth = contentView.getMeasuredWidth();
        int measuredHeight = contentView.getMeasuredHeight();

        int[] position = getPopupWindowShowPosition(startRect, endRect, translateX, translateY, targetViewSize);
        if (position[2] == 1) {
            popupWindow.update(position[0] - measuredWidth / 2, position[1], measuredWidth, measuredHeight);
        } else {
            popupWindow.update(position[0] - measuredWidth / 2, position[1] - measuredHeight, measuredWidth, measuredHeight);
        }
    }

    void visiblePopupWindowSelectMark(boolean isVisible) {
        if (popupWindowSelectMarkKey == null) {
            return;
        }
        PopupWindow popupWindow = getPopupWindow(popupWindowSelectMarkKey);
        if (popupWindow == null) {
            return;
        }
        popupWindow.getContentView().setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
    }

    @Override
    public void initHttp() {
    }

    @Override
    public void initOther() {

    }

    private void onClickListener() {
        onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.imageViewBack:
                        finish();
                        break;
                    case R.id.linearLayoutOutline:
                        selectMenu(0);
                        break;
                    case R.id.linearLayoutRead:
                        selectMenu(1);
                        break;
                    case R.id.linearLayoutMarker:
                        selectMenu(2);
                        break;
                    case R.id.linearLayoutText:
                        selectMenu(3);
                        break;
                    case R.id.linearLayoutNotes:
                        selectMenu(4);
                        break;
                    case R.id.linearLayoutEraser:
                        selectMenu(5);
                        break;
                    case R.id.linearLayoutThumbnail:
                        selectMenu(-1);
                        ThumbnailActivity.openThumbnailActivity(MainActivity.this, PDF_NAME, PDF_PASSWORD, pageNumber, THUMBNAIL_CHOOSE_REQUEST);
                        break;
                    case R.id.linearLayoutSingle:
                        updateReadModeStatus(ReadModeItem.ReadModeType.SINGLE);
                        if (isReadModeChecked(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE)) {
                            configurator.setAutoFillWhiteSpace(isReadModeChecked(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE));
                        }
                        configurator.defaultPage(pageNumber);
                        configurator.swipeHorizontal(true).load();
                        selectMenu(-1);
                        break;
                    case R.id.linearLayoutMulti:
                        updateReadModeStatus(ReadModeItem.ReadModeType.MULTI);
                        if (isReadModeChecked(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE)) {
                            configurator.setAutoFillWhiteSpace(false);
                        }
                        configurator.defaultPage(pageNumber);
                        configurator.swipeHorizontal(false).load();
                        selectMenu(-1);
                        break;
                    case R.id.linearLayoutAutoFillWhiteSpace:
                        updateReadModeStatus(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE);
                        if (isReadModeChecked(ReadModeItem.ReadModeType.SINGLE)) {
                            configurator.setAutoFillWhiteSpace(isReadModeChecked(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE)).load();
                        }
                        selectMenu(-1);
                        break;
                    case R.id.linearLayoutNight:
                        updateReadModeStatus(ReadModeItem.ReadModeType.NIGHT);
                        configurator.defaultPage(pageNumber);
                        configurator.nightMode(isReadModeChecked(ReadModeItem.ReadModeType.NIGHT)).load();
                        setNightMode(isReadModeChecked(ReadModeItem.ReadModeType.NIGHT));
                        selectMenu(-1);
                        break;
                    case R.id.linearLayoutSearch:
                        viewBinding.frameLayoutSearchAppbar.setVisibility(View.VISIBLE);
                        break;
                    case R.id.textViewSearchCancel:
                        searchContent = "";
                        viewBinding.pdfView.clearSearchArea();
                        viewBinding.layoutSearchAppbar.editTextSearch.setText("");
                        viewBinding.frameLayoutSearchAppbar.setVisibility(View.GONE);
                        break;
                    case R.id.imageViewSearchClear:
                        searchContent = "";
                        viewBinding.pdfView.clearSearchArea();
                        viewBinding.layoutSearchAppbar.editTextSearch.setText("");
                        break;
                    case R.id.imageViewSearch:
                        searchText(searchContent);
                        break;
                    case R.id.imageViewReverseLeft:
                        PenAnnotation drawingPenAnnotation = viewBinding.pdfView.removeLastDrawingPenAnnotation();
                        if (drawingPenAnnotation == null) {
                            BaseAnnotation baseAnnotation = viewBinding.pdfView.removeLastAnnotation(pageNumber, true);
                            if (baseAnnotation != null) {
                                reserveAnnotations.add(new ReserveAnnotation(ReserveAnnotationType.DRAWED, baseAnnotation, null));
                            }
                        } else {
                            reserveAnnotations.add(new ReserveAnnotation(ReserveAnnotationType.DRAWING, null, drawingPenAnnotation));
                        }
                        checkReverseRightStatus();
                        break;
                    case R.id.imageViewReverseRight:
                        if (reserveAnnotations.size() > 0) {
                            ReserveAnnotation reserveAnnotation = reserveAnnotations.remove(reserveAnnotations.size() - 1);
                            if (reserveAnnotation.getReserveAnnotationType() == ReserveAnnotationType.DRAWED) {
                                BaseAnnotation theBaseAnnotation = reserveAnnotation.getDrawedBaseAnnotation();
                                if (theBaseAnnotation != null) {
                                    theBaseAnnotation.drawed = false;
                                    viewBinding.pdfView.addLastAnnotation(theBaseAnnotation, true);
                                }
                            } else if (reserveAnnotation.getReserveAnnotationType() == ReserveAnnotationType.DRAWING) {
                                PenAnnotation theDrawingPenAnnotation = reserveAnnotation.getDrawingPenAnnotation();
                                if (theDrawingPenAnnotation != null) {
                                    theDrawingPenAnnotation.drawed = false;
                                    viewBinding.pdfView.addLastDrawingPenAnnotation(theDrawingPenAnnotation);
                                }
                            }
                        }
                        checkReverseRightStatus();
                        break;
                    case R.id.linearLayoutCollection:
                        if (isCollection(PDF_NAME, pageNumber)) {
                            removeCollectionItem(PDF_NAME, pageNumber);
                        } else {
                            addCollectionItem(PDF_NAME, "页面 " + (pageNumber + 1), pageNumber);
                            // showPopupWindowInput(viewBinding.layoutTopAppbar.linearLayoutCollection, "");
                        }
                        break;
                    default:
                        break;
                }
            }
        };
        viewBinding.layoutTopAppbar.imageViewBack.setOnClickListener(onClickListener);
        viewBinding.layoutBottomMenu.linearLayoutOutline.setOnClickListener(onClickListener);
        viewBinding.layoutBottomMenu.linearLayoutRead.setOnClickListener(onClickListener);
        viewBinding.layoutBottomMenu.linearLayoutMarker.setOnClickListener(onClickListener);
        viewBinding.layoutBottomMenu.linearLayoutText.setOnClickListener(onClickListener);
        viewBinding.layoutBottomMenu.linearLayoutNotes.setOnClickListener(onClickListener);
        viewBinding.layoutBottomMenu.linearLayoutEraser.setOnClickListener(onClickListener);
        viewBinding.layoutBottomMenu.imageViewReverseLeft.setOnClickListener(onClickListener);
        viewBinding.layoutBottomMenu.imageViewReverseRight.setOnClickListener(onClickListener);
        viewBinding.layoutReadMode.linearLayoutThumbnail.setOnClickListener(onClickListener);
        viewBinding.layoutReadMode.linearLayoutSingle.setOnClickListener(onClickListener);
        viewBinding.layoutReadMode.linearLayoutMulti.setOnClickListener(onClickListener);
        viewBinding.layoutReadMode.linearLayoutAutoFillWhiteSpace.setOnClickListener(onClickListener);
        viewBinding.layoutReadMode.linearLayoutNight.setOnClickListener(onClickListener);
        viewBinding.layoutTopAppbar.linearLayoutCollection.setOnClickListener(onClickListener);
        viewBinding.layoutTopAppbar.linearLayoutSearch.setOnClickListener(onClickListener);
        viewBinding.layoutSearchAppbar.textViewSearchCancel.setOnClickListener(onClickListener);
        viewBinding.layoutSearchAppbar.imageViewSearchClear.setOnClickListener(onClickListener);
        viewBinding.layoutSearchAppbar.imageViewSearch.setOnClickListener(onClickListener);
    }

    private void checkReverseRightStatus() {
        if (reserveAnnotations.size() > 0) {
            viewBinding.layoutBottomMenu.imageViewReverseRight.setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.mainColorText_default));
        } else {
            viewBinding.layoutBottomMenu.imageViewReverseRight.setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.textView_hint));
        }
    }

    private void selectMenu(int index) {
        int defaultTextColor = ContextCompat.getColor(this, R.color.mainColorText_default);
        int selectColor = ContextCompat.getColor(this, R.color.menu_select_default);
        viewBinding.layoutBottomMenu.linearLayoutOutline.setBackground(null);
        viewBinding.layoutBottomMenu.linearLayoutRead.setBackground(null);
        viewBinding.layoutBottomMenu.linearLayoutMarker.setBackground(null);
        viewBinding.layoutBottomMenu.linearLayoutText.setBackground(null);
        viewBinding.layoutBottomMenu.linearLayoutNotes.setBackground(null);
        viewBinding.layoutBottomMenu.linearLayoutEraser.setBackground(null);

        viewBinding.layoutBottomMenu.textViewOutline.setTextColor(defaultTextColor);
        viewBinding.layoutBottomMenu.textViewRead.setTextColor(defaultTextColor);
        viewBinding.layoutBottomMenu.textViewMarker.setTextColor(defaultTextColor);
        viewBinding.layoutBottomMenu.textViewText.setTextColor(defaultTextColor);
        viewBinding.layoutBottomMenu.textViewNotes.setTextColor(defaultTextColor);
        viewBinding.layoutBottomMenu.textViewEraser.setTextColor(defaultTextColor);

        viewBinding.layoutBottomMenu.imageViewOutline.setColorFilter(defaultTextColor);
        viewBinding.layoutBottomMenu.imageViewRead.setColorFilter(defaultTextColor);
        viewBinding.layoutBottomMenu.imageViewMarker.setColorFilter(defaultTextColor);
        viewBinding.layoutBottomMenu.imageViewText.setColorFilter(defaultTextColor);
        viewBinding.layoutBottomMenu.imageViewNotes.setColorFilter(defaultTextColor);
        viewBinding.layoutBottomMenu.imageViewEraser.setColorFilter(defaultTextColor);

        if (index != 1) {
            viewBinding.frameLayoutReadMode.setVisibility(View.GONE);
        }
        if (index == -1) {
            viewBinding.frameLayoutPenOperating.setVisibility(View.GONE);
            viewBinding.frameLayoutTextOperating.setVisibility(View.GONE);
            return;
        }
        if (index == 0 || index == 1 || index == 4 || index == 5) {
            viewBinding.frameLayoutPenOperating.setVisibility(View.GONE);
            viewBinding.frameLayoutTextOperating.setVisibility(View.GONE);
        }
        if ((selectMenu == 2 || selectMenu == 3 || selectMenu == 4) && (selectMenu != index)) {
            resetViewMode();
            viewBinding.pdfView.setEnableNotes(false);
            viewBinding.pdfView.savePenDrawing();
        }
        switch (index) {
            case 0:
                if (viewBinding.drawerLayout.isDrawerOpen(Gravity.LEFT)) {
                    viewBinding.drawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    viewBinding.drawerLayout.openDrawer(Gravity.LEFT);
                }
                break;
            case 1:
                if (viewBinding.frameLayoutReadMode.getVisibility() == View.VISIBLE) {
                    viewBinding.frameLayoutReadMode.setVisibility(View.GONE);
                } else {
                    viewBinding.layoutBottomMenu.linearLayoutRead.setBackgroundResource(R.drawable.menu_select_background);
                    viewBinding.layoutBottomMenu.imageViewRead.setColorFilter(selectColor);
                    viewBinding.layoutBottomMenu.textViewRead.setTextColor(selectColor);
                    viewBinding.frameLayoutReadMode.setVisibility(View.VISIBLE);
                }
                break;
            case 2:
                if (viewBinding.frameLayoutPenOperating.getVisibility() == View.VISIBLE) {
                    viewBinding.frameLayoutPenOperating.setVisibility(View.GONE);
                    resetViewMode();
                } else {
                    viewBinding.layoutBottomMenu.circleView.setBackgroundColor(penColor);
                    viewBinding.layoutBottomMenu.linearLayoutMarker.setBackgroundResource(R.drawable.menu_select_background);
                    viewBinding.layoutBottomMenu.imageViewMarker.setColorFilter(selectColor);
                    viewBinding.layoutBottomMenu.textViewMarker.setTextColor(selectColor);
                    viewBinding.frameLayoutTextOperating.setVisibility(View.GONE);
                    if (pen != null) {
                        viewBinding.pdfView.setPenMode(pen);
                    }
                    viewBinding.frameLayoutPenOperating.setVisibility(View.VISIBLE);
                }
                break;
            case 3:
                if (viewBinding.frameLayoutTextOperating.getVisibility() == View.VISIBLE) {
                    viewBinding.frameLayoutTextOperating.setVisibility(View.GONE);
                    resetViewMode();
                } else {
                    viewBinding.layoutBottomMenu.circleView.setBackgroundColor(textColor);
                    viewBinding.layoutBottomMenu.linearLayoutText.setBackgroundResource(R.drawable.menu_select_background);
                    viewBinding.layoutBottomMenu.imageViewText.setColorFilter(selectColor);
                    viewBinding.layoutBottomMenu.textViewText.setTextColor(selectColor);
                    viewBinding.frameLayoutPenOperating.setVisibility(View.GONE);
                    if (textPen != null) {
                        viewBinding.pdfView.setTextMode(textPen);
                    }
                    viewBinding.frameLayoutTextOperating.setVisibility(View.VISIBLE);
                }
                break;
            case 4:
                resetViewMode();
                if (viewBinding.layoutBottomMenu.linearLayoutNotes.getTag() != null && (boolean) viewBinding.layoutBottomMenu.linearLayoutNotes.getTag()) {
                    viewBinding.layoutBottomMenu.linearLayoutNotes.setTag(false);
                    viewBinding.pdfView.setEnableNotes(false);
                } else {
                    viewBinding.layoutBottomMenu.linearLayoutNotes.setBackgroundResource(R.drawable.menu_select_background);
                    viewBinding.layoutBottomMenu.imageViewNotes.setColorFilter(selectColor);
                    viewBinding.layoutBottomMenu.textViewNotes.setTextColor(selectColor);
                    viewBinding.layoutBottomMenu.linearLayoutNotes.setTag(true);
                    viewBinding.pdfView.setEnableNotes(true);
                }
                break;
            case 5:
                if (viewBinding.layoutBottomMenu.linearLayoutEraser.getTag() != null && (boolean) viewBinding.layoutBottomMenu.linearLayoutEraser.getTag()) {
                    viewBinding.layoutBottomMenu.linearLayoutEraser.setTag(false);
                    resetViewMode();
                } else {
                    viewBinding.layoutBottomMenu.linearLayoutEraser.setBackgroundResource(R.drawable.menu_select_background);
                    viewBinding.layoutBottomMenu.imageViewEraser.setColorFilter(selectColor);
                    viewBinding.layoutBottomMenu.textViewEraser.setTextColor(selectColor);
                    viewBinding.layoutBottomMenu.linearLayoutEraser.setTag(true);
                    viewBinding.pdfView.setEraserMode(new PenRectEraser(40, 40, false));
                }
                break;
            default:
                break;
        }
        selectMenu = index;
    }

    private boolean isEraserMode() {
        return viewBinding.pdfView.getFunction() == PDFView.Function.ERASER;
    }

    private void resetViewMode() {
        viewBinding.pdfView.savePenDrawing();
        viewBinding.pdfView.setViewerMode();
        if (eraserSuccess) {
            eraserSuccess = false;
            saveAnnotationData();
        }
    }

    private void initPenColorViews() {
        int itemWidth = (int) getResources().getDimension(R.dimen.layout_pen_operating_circle_width);
        int operatingHeight = (int) (getResources().getDimension(R.dimen.layout_pen_operating_height) * 0.8);
        if (operatingHeight < itemWidth) {
            itemWidth = operatingHeight;
        }
        List<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.pen_color_1));
        colors.add(getResources().getColor(R.color.pen_color_2));
        colors.add(getResources().getColor(R.color.pen_color_3));
        colors.add(getResources().getColor(R.color.pen_color_4));
        colors.add(getResources().getColor(R.color.pen_color_5));
        colors.add(getResources().getColor(R.color.pen_color_6));
        colors.add(getResources().getColor(R.color.pen_color_7));
        if (penColor == 0) {
            penColor = getResources().getColor(R.color.pen_color_1);
        }
        viewBinding.layoutPenOperating.textViewTextSize.setText(penSize + "px");
        viewBinding.layoutPenOperating.mySeekBar.setProgress(penSize);
        circleViews.clear();
        int borderColor = getResources().getColor(R.color.circleViewBorder_default);
        for (int i = 0; i < colors.size(); i++) {
            CircleView circleView = new CircleView(this);
            circleView.setBackgroundColor(colors.get(i));
            circleView.setInnerCirclePercent(0.6f);
            circleView.setBorderColor(borderColor);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(itemWidth, itemWidth);
            final int index = i;
            circleView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updatePenColor(circleViews, index, false);
                }
            });
            viewBinding.layoutPenOperating.linearLayoutPenColor.addView(circleView, layoutParams);
            if (i == 0) {
                circleView.setChecked(true);
            }
            circleViews.add(circleView);
        }
        if (pen == null && circleViews.size() > 0) {
            updatePenColor(circleViews, selectPenColorIndex, true);
        }
    }

    private void initTextColorViews() {
        int itemWidth = (int) getResources().getDimension(R.dimen.layout_pen_operating_circle_width);
        int operatingHeight = (int) (getResources().getDimension(R.dimen.layout_pen_operating_height) * 0.8);
        if (operatingHeight < itemWidth) {
            itemWidth = operatingHeight;
        }
        List<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.pen_color_1));
        colors.add(getResources().getColor(R.color.pen_color_2));
        colors.add(getResources().getColor(R.color.pen_color_3));
        colors.add(getResources().getColor(R.color.pen_color_4));
        colors.add(getResources().getColor(R.color.pen_color_5));
        colors.add(getResources().getColor(R.color.pen_color_6));
        colors.add(getResources().getColor(R.color.pen_color_7));
        if (textColor == 0) {
            textColor = getResources().getColor(R.color.pen_color_1);
        }
        viewBinding.layoutTextOperating.textViewTextSize.setText(textSize + "px");
        viewBinding.layoutTextOperating.mySeekBar.setProgress(textSize);
        textCircleViews.clear();
        int borderColor = getResources().getColor(R.color.circleViewBorder_default);
        for (int i = 0; i < colors.size(); i++) {
            CircleView circleView = new CircleView(this);
            circleView.setBackgroundColor(colors.get(i));
            circleView.setInnerCirclePercent(0.6f);
            circleView.setBorderColor(borderColor);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(itemWidth, itemWidth);
            final int index = i;
            circleView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateTextColor(textCircleViews, index, false);
                }
            });
            viewBinding.layoutTextOperating.linearLayoutPenColor.addView(circleView, layoutParams);
            if (i == 0) {
                circleView.setChecked(true);
            }
            textCircleViews.add(circleView);
        }
        if (textPen == null && textCircleViews.size() > 0) {
            updateTextColor(textCircleViews, selectTextColorIndex, true);
        }
    }

    private void updatePenColor(List<CircleView> circleViews, int index, boolean isInit) {
        if (circleViews == null || index > circleViews.size() - 1 || index < 0) {
            return;
        }
        for (int i = 0; i < circleViews.size(); i++) {
            CircleView circleView = circleViews.get(i);
            circleView.setChecked(i == index);
        }
        CircleView circleView = circleViews.get(index);
        int color = circleView.getBackgroundColor();
        penColor = color;
        viewBinding.layoutBottomMenu.circleView.setBackgroundColor(color);
        pen = PenBuilder.brushPenBuilder().setColor(penColor).setPenWidthScale(PEN_SCALE_DEFAULT * penSize).build();
        if (!isInit) {
            viewBinding.pdfView.setPenMode(pen);
        }
        selectPenColorIndex = index;
    }

    private void updateTextColor(List<CircleView> circleViews, int index, boolean isInit) {
        if (circleViews == null || index > circleViews.size() - 1 || index < 0) {
            return;
        }
        for (int i = 0; i < circleViews.size(); i++) {
            CircleView circleView = circleViews.get(i);
            circleView.setChecked(i == index);
        }
        CircleView circleView = circleViews.get(index);
        int color = circleView.getBackgroundColor();
        textColor = color;
        viewBinding.layoutBottomMenu.circleView.setBackgroundColor(color);
        textPen = PenBuilder.textPenBuilder().setColor(color).setFontSize(textSize).build();
        if (!isInit) {
            viewBinding.pdfView.setTextMode(textPen);
        }
        selectTextColorIndex = index;
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        if (pageNumber != page) {
            viewBinding.pdfView.savePenDrawing();
        }
        pageNumber = page;
        if (imageThumbnailRecyclerAdapter != null && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            imageThumbnailRecyclerAdapter.setSelectPage(page);
            imageThumbnailRecyclerAdapter.notifyDataSetChanged();
        }
        updateCollection();
    }

    private void updateCollection() {
        if (isCollection(PDF_NAME, pageNumber)) {
            viewBinding.layoutTopAppbar.imageViewCollection.setImageResource(R.mipmap.collection_select);
        } else {
            viewBinding.layoutTopAppbar.imageViewCollection.setImageResource(R.mipmap.collection_unselect);
        }
    }

    private void saveAnnotationData() {
        String result = GsonUtils.toJson(OPEN_OPTIMIZATION_ANNOTATION ? viewBinding.pdfView.getAllOptimizationAnnotation() : viewBinding.pdfView.getAllAnnotation());
        CacheDiskUtils.getInstance().put(PDF_NAME, result);
    }

    public void showPopupWindowInputNotes(View view, boolean isEdit, String defaulText, String id, NotesRemarkInfo notesRemarkInfo) {
        String title = getString(R.string.popupwindow_input_notes_title_text);
        PopupWindowUtil.showPopupWindowBottomInput(MainActivity.this, view.getRootView(), view, title, defaulText,
                new PopupWindowUtil.OnShowPopupWindowBottomInputListener() {
                    @Override
                    public void onCancelClick(PopupWindow popupWindow, View view) {
                        popupWindow.dismiss();
                    }

                    @Override
                    public void onOkClick(PopupWindow popupWindow, View view, String text) {
                        popupWindow.dismiss();
                        if (isEdit) {
                            if (!text.equals("")) {
                                editNotesItem(PDF_NAME, id, text);
                            } else {
                                removeNotesItem(PDF_NAME, id);
                            }
                        } else {
                            if (!text.equals("")) {
                                addNotesItem(PDF_NAME, text, notesRemarkInfo);
                            }
                        }
                    }

                    @Override
                    public void onDismiss(PopupWindow popupWindow, View view) {

                    }
                });
    }

    public void showCollectionPopupWindowInput(View view, String defaultText, CollectionItem collectionItem) {
        String title = getString(R.string.popupwindow_input_title_text);
        PopupWindowUtil.showPopupWindowInput(MainActivity.this, view.getRootView(), view, title, defaultText,
                new PopupWindowUtil.OnShowPopupWindowInputListener() {
                    @Override
                    public void onCancelClick(PopupWindow popupWindow, View view) {
                        popupWindow.dismiss();
                    }

                    @Override
                    public void onOkClick(PopupWindow popupWindow, View view, String text) {
                        popupWindow.dismiss();
                        if (text.equals("")) {
                            removeCollectionItem(PDF_NAME, pageNumber);
                        } else {
                            editCollectionItem(PDF_NAME, text, collectionItem);
                        }
                    }

                    @Override
                    public void onDismiss(PopupWindow popupWindow, View view) {

                    }
                });
    }


    private List<AnnotationBean> getAnnotationData() {
        List<AnnotationBean> annotations = new ArrayList<>();
        String saveJson = CacheDiskUtils.getInstance().getString(PDF_NAME, null);
        if (ObjectUtils.isNotEmpty(saveJson)) {
            annotations = GsonUtils.fromJson(saveJson, new TypeToken<List<AnnotationBean>>() {
            }.getType());
        }
        return annotations;
    }

    private void doVibrate() {
        Vibrator vibrator = (Vibrator) this.getSystemService(Service.VIBRATOR_SERVICE);
        vibrator.vibrate(100);
    }

    private int[] getPopupWindowShowPosition(RectF startRect, RectF endRect, float translateX, float translateY, float targetViewSize) {
        int[] location = new int[2];
        viewBinding.pdfView.getLocationInWindow(location);

        float startTop = location[1] + startRect.top + translateY;
        float endBottom = location[1] + endRect.bottom + translateY;

        float startLeft = location[0] + startRect.left + translateX;
        float endRight = location[0] + endRect.right + translateX;

        int screenHeight = getScreenHeight(MainActivity.this);
        int x, y, isUp;
        if (endBottom <= screenHeight * 0.666) {
            x = (int) endRight;
            y = (int) (endBottom + targetViewSize);
            isUp = 1;
        } else {
            x = (int) startLeft;
            y = (int) startTop;
            isUp = 0;
        }
        popupWindowPdfPositionStatus.setX(x);
        popupWindowPdfPositionStatus.setY(y);
        popupWindowPdfPositionStatus.setUp(isUp == 1);
        return new int[]{x, y, isUp};
    }

    void openPdf(@NonNull String assetFileName, @Nullable String password) {
        configurator = viewBinding.pdfView.fromAsset(assetFileName);
        configurator.password(password)
                .defaultPage(pageNumber)
                .swipeHorizontal(true)
                .pageFling(false)
                .pageSnap(true)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .autoSpacing(true)//开启后批注计算可能还有一些地方可以改进
                .drawingPenOptimize(false)
//               .scrollHandle(new DefaultScrollHandle(this))
//                .spacing(10) // in dp
                .onPageError(this)
                .pageFitPolicy(FitPolicy.WIDTH)
                .setAutoFillWhiteSpace(false)
                .setLoadAfterCheckWhiteSpace(true)
                .setUseMinWhiteSpaceZoom(false)
                .setInitWhiteSpaceOptimization(true)
                .setWhiteSpaceRenderBestQuality(false)
                .setWhiteSpaceRenderThumbnailRatio(0.3f)
                .setWhiteSpaceRenderPageCountWhenOptimization(12)
                .setShowLoadingWhenWhiteSpaceRender(true)
                .setEditTextNormalColor(getResources().getColor(R.color.edit_text_remark_theme))
                .setEditTextRemarkThemeColor(getResources().getColor(R.color.edit_text_remark_theme))
                .setReadOnlyMode(false)
                .setSingleZoom(true)
                .setAnnotationRenderingArea(1)
                .setSupportCustomRendering(true)
                .onLoad(this)
                .onError(new OnErrorListener() {
                    @Override
                    public void onError(Throwable t) {
                        ToastUtil.showShortToast(MainActivity.this, getString(R.string.file_open_error));
                        viewBinding.loadProgressBar.setVisibility(View.INVISIBLE);
                    }
                });
        initPdfConfig();
        configurator.load();
    }

    private void initPdfConfig() {
        if (readModeItems.size() == 0) {
            return;
        }
        configurator.defaultPage(pageNumber);
        for (int i = 0; i < readModeItems.size(); i++) {
            ReadModeItem readModeItem = readModeItems.get(i);
            if (readModeItem.getType() == ReadModeItem.ReadModeType.SINGLE) {
                if (readModeItem.isCheck()) {
                    configurator.swipeHorizontal(true).setAutoFillWhiteSpace(isReadModeChecked(ReadModeItem.ReadModeType.AUTO_FILL_WHITE_SPACE));
                }
            } else if (readModeItem.getType() == ReadModeItem.ReadModeType.MULTI) {
                if (readModeItem.isCheck()) {
                    configurator.swipeHorizontal(false);
                }
            } else if (readModeItem.getType() == ReadModeItem.ReadModeType.NIGHT) {
                if (readModeItem.isCheck()) {
                    configurator.nightMode(true);
                } else {
                    configurator.nightMode(false);
                }
            }
        }
    }

    @Override
    public void loadComplete(int nbPages) {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            viewBinding.recyclerViewThumbnail.setLayoutManager(new LinearLayoutManager(this));
            if (imageThumbnailRecyclerAdapter == null) {
                imageThumbnailRecyclerAdapter = new ImageThumbnailRecyclerAdapter(this, viewBinding.pdfView, new ImageThumbnailRecyclerAdapter.OnImageThumbnailItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position, RenderingCustomHandler.RenderingCustomPageInfo renderingCustomPageInfo) {
                        viewBinding.pdfView.savePenDrawing();
                        jumpToPageWithAutoFillCheck(position);
                    }
                }, bitmapMemoryCacheHelper, ThumbnailActivity.getAllRenderingCustomPageInfos(viewBinding.pdfView), pageNumber, (int) (getResources().getDimension(R.dimen.activity_main_thumbnail_view_width)));
            }
            viewBinding.recyclerViewThumbnail.setAdapter(imageThumbnailRecyclerAdapter);
        }
    }

    @Override
    public void onPageError(int page, Throwable t) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        if (requestCode == THUMBNAIL_CHOOSE_REQUEST) {
            int page = intent.getIntExtra(RESULT_PAGE_KEY, -1);
            if (page != -1) {
                jumpToPageWithAutoFillCheck(page);
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
    }

    public void jumpToPageWithAutoFillCheck(int page) {
        viewBinding.pdfView.addAnimationEndRunnable("jumpToPage", new Runnable() {
            @Override
            public void run() {
                viewBinding.pdfView.jumpToPageWithAutoFillCheck(page);
            }
        });
    }

    private void searchText(String text) {
        if (text == null || text.equals("")) {
            viewBinding.pdfView.clearSearchArea();
            return;
        }
        viewBinding.pdfView.searchText(text, 3, new OnSearchTextListener() {
            @Override
            public void onProcess() {
                viewBinding.searchProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onResult(SearchTextInfo searchTextInfo) {
                viewBinding.searchProgressBar.setVisibility(View.INVISIBLE);
                if (searchTextInfo == null) {
                    ToastUtil.showShortToast(MainActivity.this, getString(R.string.search_result_empty));
                    return;
                }
                if (pageNumber != searchTextInfo.getPage()) {
                    jumpToPageWithAutoFillCheck(searchTextInfo.getPage());
                }
                viewBinding.pdfView.drawSearchArea(searchTextInfo);
            }

            @Override
            public void onCancel() {
                viewBinding.searchProgressBar.setVisibility(View.INVISIBLE);
            }
        });
    }

    private void searchTagSectionInfos(String tag) {
        if (tag == null || tag.equals("")) {
            viewBinding.pdfView.clearSearchArea();
            showSearchResult(tag, null);
            return;
        }
        viewBinding.pdfView.searchTagSectionInfos(2, tag, 0, 5, new OnSearchTagSectionsListener() {
            @Override
            public void onProcess() {
                viewBinding.searchProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onResult(List<TagSectionInfo> tagSectionInfos) {
                viewBinding.searchProgressBar.setVisibility(View.INVISIBLE);
                if (tagSectionInfos == null) {
                    return;
                }
                if (!viewBinding.drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                    viewBinding.drawerLayout.openDrawer(Gravity.RIGHT);
                }
                showSearchResult(tag, tagSectionInfos);
            }

            @Override
            public void onCancel() {
                viewBinding.searchProgressBar.setVisibility(View.INVISIBLE);
            }
        });
    }

    private void showSearchResult(String tag, List<TagSectionInfo> tagSectionInfos) {
        if (tagSectionInfos == null) {
            tagSectionInfos = new ArrayList<>();
        }
        viewBinding.layoutSearchResultView.textViewTips.setText(getString(R.string.search_total_count_text) + " " + tagSectionInfos.size());
        searchResultRecyclerAdapter = new SearchResultRecyclerAdapter(MainActivity.this, SearchResultItem.convertToSearchResultItems(tag, tagSectionInfos), new SearchResultRecyclerAdapter.OnSearchResultItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, int position, TagSectionInfo tagSectionInfo) {
                if (pageNumber != tagSectionInfo.getPage()) {
                    jumpToPageWithAutoFillCheck(tagSectionInfo.getPage());
                }
                SearchTextInfo searchTextInfo = new SearchTextInfo(tagSectionInfo.getStart(), tagSectionInfo.getEnd(), tagSectionInfo.getData(), tagSectionInfo.getPage());
                viewBinding.pdfView.drawSearchArea(searchTextInfo);
            }
        });
        viewBinding.layoutSearchResultView.recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        viewBinding.layoutSearchResultView.recyclerView.setAdapter(searchResultRecyclerAdapter);
    }
}